package com.zf.shuashua.ui.popup;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.provider.Settings;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.aliyun.common.utils.DensityUtil;
import com.lxj.xpopup.core.CenterPopupView;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.umeng.analytics.MobclickAgent;
import com.zf.shuashua.R;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.manager.AdAutoTouchManager;
import com.zf.shuashua.manager.CalendarManager;

import java.util.HashMap;
import java.util.Map;

/**
 * 提现成功
 */
public class BillSuccessPopup extends CenterPopupView {

    private TextView btnTitle, tvHint;
    private FrameLayout advert_container;
    private OnPopupListener mListener;
    private Boolean isNewUser;

    private boolean isCalendarReminded = false;
    private ImageView ivBg;
    private LinearLayout layoutRemind;
    private TextView tvStartRemind;
    private TextView tvNoMoreRemind;

    private FragmentActivity activity;
    private View view;

    public BillSuccessPopup(@NonNull FragmentActivity context, boolean isNewUser) {
        super(context);
        activity = context;
        this.isNewUser = isNewUser;
    }

    public void setPopupListener(OnPopupListener listener) {
        this.mListener = listener;
    }

    public void addAdvertView(View view) {
        this.view = view;
        advert_container.removeAllViews();
        advert_container.addView(view);
        if (isCalendarReminded) {
            btnTitle.setVisibility(VISIBLE);
        }
    }

    public void loadAdvertFail() {
        advert_container.setVisibility(GONE);
        if (isCalendarReminded) {
            btnTitle.setVisibility(VISIBLE);
        }
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.bill_popup_success;
    }

    @Override
    protected void onCreate() {
        super.onCreate();

        isCalendarReminded = Store.getInstance().isCalendarReminded();
        setupView();
    }

    private void setupView() {
        btnTitle = findViewById(R.id.btTitle);
        advert_container = findViewById(R.id.advert_container);
        ivBg = findViewById(R.id.img_backdrop);
        layoutRemind = findViewById(R.id.layout_remind);
        tvStartRemind = findViewById(R.id.tv_start_remind);
        tvNoMoreRemind = findViewById(R.id.tv_no_more);
        btnTitle.setOnClickListener(v -> {
            if (!AdAutoTouchManager.getInstance().randomAutoClickAd(view)) {
                dismiss();
                if (mListener != null) {
                    mListener.onNext();
                }
            }
        });
        tvHint = findViewById(R.id.tv_hint);
        try{
            if(isNewUser){
                String title = activity.getString(R.string.bill_success_tip_new);
                SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(title);
                int start = title.lastIndexOf("提");
                spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.RED), start, title.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                tvHint.setText(spannableStringBuilder);
            }else{
                tvHint.setText(activity.getString(R.string.bill_success_tip));
            }
        }catch (Exception ignored){

        }

//        if (Store.getInstance().getTP_AD()) {
//            findViewById(R.id.flCancel).setOnClickListener(v -> {
//                dismiss();
//                if (mListener != null) {
//                    mListener.onNext();
//                }
//            });
//        } else {
//            btnTitle.setOnClickListener(v -> {
//                dismiss();
//                if (mListener != null) {
//                    mListener.onNext();
//                }
//            });
//        }


        if (!isCalendarReminded) {
            ivBg.getLayoutParams().height = DensityUtil.dip2px(getContext(), 250);
            ivBg.requestLayout();

            layoutRemind.setVisibility(VISIBLE);
        }

        tvNoMoreRemind.setOnClickListener(v -> {
            Store.getInstance().setCalendarReminded(true);
            dismiss();
        });

        tvStartRemind.setOnClickListener(v -> {
            handlerCalendarRemind();
        });

    }


    /**
     * 处理日历提醒
     */
    @SuppressLint("CheckResult")
    public void handlerCalendarRemind() {
        // 请求权限
        new RxPermissions(activity).request(new String[]{
                Manifest.permission.READ_CALENDAR,
                Manifest.permission.WRITE_CALENDAR})
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        CalendarManager.getInstance().startWithdrawalCalendarEvent(getContext());
                        Store.getInstance().setCalendarReminded(true);
                        dismiss();
                        Map<String, Object> map = new HashMap<>();
                        map.put("phone", Store.getInstance().getUserPhone());//自定义参数：音乐类型，值：流行
                        map.put("uid", Store.getInstance().getuserId()); //uid
                        map.put("type", android.os.Build.MODEL); //手机型号
                        MobclickAgent.onEventObject(activity, "schedule", map);

                    } else {
                        Toast.makeText(getContext(), "请允许日历权限", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.parse("package:" + getContext().getPackageName()));
                        if (!isIntentAvailable(intent)) return;
                        getContext().startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                    }
                });
    }

    private boolean isIntentAvailable(final Intent intent) {
        return getContext()
                .getPackageManager()
                .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
                .size() > 0;
    }

}

